let Config = require('./Config');
let Util = require('./Util');
let NekoBoxManager = {};

NekoBoxManager.hasVMess = function(){
    let vmess = text("VMess").findOne(5000);
    if(vmess == null){
        console.log('不存在VMess');
        return false;
    }else{
        console.log('存在VMess');
        return true;
    }
}

NekoBoxManager.testFocus = function(){
    Util.idClick("action_add");
    sleep(500);
    auto(); // 确保无障碍服务已开启
    // 查找当前界面中所有已获得焦点的控件
    let focusedWidget = classNameMatches(/.*/).focused().findOne();

    if (focusedWidget) {
        let className = focusedWidget.className();
        console.log("焦点组件类型:", className);
        
        // 判断类型
        if (className === "android.widget.EditText") {
            console.log("输入框");
        } else if (className.endsWith("Button")) {
            console.log("按钮");
        }
    } else {
        console.log("未找到焦点组件");
    }
}

NekoBoxManager.createVMess = function(ip){
    // 点击 +
    Util.idClick("action_add");
    sleep(500);
    Util.textClick('手动输入');
    sleep(500);
    Util.textClick('VMess');
    console.log('1111111');
// ------------服务器IP填写
    Util.textClick('服务器');
    sleep(500);
    console.log('2222222');
    
    Util.setCurrentEditText(ip);
    sleep(500);
    Util.textClick('确定');
    sleep(500);
// ------------服务器端口填写
    Util.textClick('服务器端口');
    sleep(500);
    Util.setCurrentEditText(Config.VMessPort.toString());
    sleep(500);
    Util.textClick('确定');
// -------------用户ID填写
    sleep(500);
    Util.textClick('用户ID');
    sleep(500);
    Util.setCurrentEditText(Config.VMessUserId);
    sleep(500);
    Util.textClick('确定');
    sleep(500);
    Util.idClick("action_apply");
    sleep(500);
    Util.textClick("VMess");
    sleep(500);

}

NekoBoxManager.connect = function(){
    requestScreenCapture();
    let imgIcon = images.read(Config.LocalConnectIconPath);
    if(!imgIcon){
        imgIcon = Util.download(Config.RemoteConnectIconPath,Config.LocalConnectIconPath);
        if(imgIcon){
            imgIcon = images.read(Config.LocalConnectIconPath);
        }
    }
    let imgScreen = captureScreen();
    let p = findImage(imgScreen,imgIcon);
    if(p == null){
        console.log("没找到");
    }else{
        console.log("找到了 p = " , p);
        console.log("p.x = " , p.x, " p.y = " , p.y);
        press(p.x + 40,p.y + 40,100);
        console.log("click finished!!!");
    }
}

NekoBoxManager.disconnect = function(){
    Util.clearAppData();
}

module.exports = NekoBoxManager;